package com.wyvoid.forum.web.action.user;

import com.wyvoid.forum.web.action.BaseAction;
import com.wyvoid.forum.service.IUserService;
import com.wyvoid.forum.domain.User;
import com.wyvoid.forum.domain.UserProfile;
import com.wyvoid.forum.domain.SessionUser;
import com.wyvoid.forum.exception.user.UserExistsException;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.DateTypeConverter;
import net.sourceforge.stripes.integration.spring.SpringBean;
import org.apache.commons.lang.StringUtils;

import java.util.Date;

/**
 * 论坛用户注册
 * <p>51void.com</p>
 * User:cjp
 * Date: 2007-5-14
 * Time: 21:58:33
 */
@UrlBinding(value = "/user/register.do")
public class RegisterAction extends BaseAction {
    @ValidateNestedProperties({
    @Validate(field = "username", required = true, maxlength = 50),
    @Validate(field = "password", required = true, minlength = 5, maxlength = 20),
    @Validate(field = "nickname", required = true, maxlength = 50),
    @Validate(field = "email", required = true, maxlength = 50),
    @Validate(field = "question", required = true, maxlength = 50),
    @Validate(field = "answer", required = true, maxlength = 50)
            })
    private User user;

    @ValidateNestedProperties({
    @Validate(field = "birthDay", required = false, converter = DateTypeConverter.class)
            })
    private UserProfile userProfile;

    private IUserService userService;

    @Validate(expression = "this == user.password")
    private String confirmPassword;

    /*@Validate(required = true)
    private String reg_agreement;*/

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public UserProfile getUserProfile() {
        return userProfile;
    }

    public void setUserProfile(UserProfile userProfile) {
        this.userProfile = userProfile;
    }

    @SpringBean
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    /* public String getReg_agreement() {
        return reg_agreement;
    }

    public void setReg_agreement(String reg_agreement) {
        this.reg_agreement = reg_agreement;
    }*/

    @DefaultHandler
    public Resolution register() {
        try {
            user.setLastLoginIp(context.getRequest().getRemoteAddr());
            if(userProfile==null){
                userProfile=new UserProfile();
            }
            userService.createUser(user, userProfile);

            SessionUser sessionUser=new SessionUser(user.getId(),user.getNickname(),SessionUser.ONLINE);
            sessionUser.setLastLoginTime(new Date());
            getContext().setUser(sessionUser);
            String forward = context.getRequest().getParameter("forward");
            if (StringUtils.isNotBlank(forward)) {
                return new RedirectResolution(forward, false);
            } else {
                return new RedirectResolution("/");
            }
        } catch (UserExistsException e) {
            log.error("user register failure because username already exists");
            getContext().getValidationErrors().add("user.msn", new LocalizableError("user.exists"));
            return getContext().getSourcePageResolution();
        }
        //return new RedirectResolution("/");
    }

    @DontValidate
    public Resolution registerForm() {
        if (user == null || user.getId() == 0) {
            user = new User();
        } else {
            user = userService.getUser(user.getId());
        }
        String forward = context.getRequest().getParameter("referer");
        if (forward == null) {
            forward = getForwardUrl();
        }
        if (StringUtils.indexOf(forward, "/user/") == -1) {
            context.getRequest().setAttribute("forward", forward);
        }
        return getBBSResolution("user/signupForm");
    }

    @DontValidate
    public Resolution checkUserExist() {
        String username = context.getRequest().getParameter("user.username");
        boolean exist = false;
        if (StringUtils.isNotBlank(username) && userService.getUser(username) != null) {
            exist = true;
        }
        context.getResponse().setHeader("Pragma", "No-cache");
        context.getResponse().setHeader("Cache-Control", "no-cache");
        context.getResponse().setDateHeader("Expires", 0);
        return new StreamingResolution("text", String.valueOf(exist));
    }
}
